﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WaitCursor
{
    [TemplateVisualState(Name = "Visible", GroupName = "Common")]
    [TemplateVisualState(Name = "Collapsed", GroupName = "Common")]
    public class WaitCursorControl : Control, INotifyPropertyChanged
    {
        #region Fields

        private Visibility _previousVisibility = Visibility.Visible;

        #endregion Fields
        #region Constructors

        public WaitCursorControl()
        {
            this.DefaultStyleKey = typeof(WaitCursorControl);
            _previousVisibility = this.Visibility;
            this.Cursor = Cursors.Wait;
            this.LayoutUpdated += new EventHandler(OnControlLayoutUpdated);
        }

        #endregion Constructors
        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion INotifyPropertyChanged
        #region Properties

        public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(WaitCursorControl), new PropertyMetadata(OnTextPropertyChanged));
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        private static void OnTextPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            WaitCursorControl control = sender as WaitCursorControl;
            if (control != null)
            {
                control.NotifyPropertyChanged("Text");
            }
        }

        #endregion Properties
        #region Methods

        private void OnControlLayoutUpdated(object sender, EventArgs e)
        {
            if (_previousVisibility != this.Visibility)
            {
                if (this.Visibility == Visibility.Collapsed)
                {
                    VisualStateManager.GoToState(this, "Collapsed", true);
                }
                else
                {
                    VisualStateManager.GoToState(this, "Visible", true);
                }

                _previousVisibility = this.Visibility;
            }
        }

        #endregion Methods
    }
}
